package com.xunlai.infra.permission.manager.sercurity;

import com.xunlai.infra.permission.common.constant.ExtendClaimsConstants;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author liang
 * @date 12/16/22 11:29 AM
 */
public class EnhanceJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> {

    private final Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();


    @Override
    public Collection<GrantedAuthority> convert(Jwt source) {
        Collection<GrantedAuthority> convert = jwtGrantedAuthoritiesConverter.convert(source);
        List<String> roles = source.getClaimAsStringList(ExtendClaimsConstants.ROLES);
        Collection<GrantedAuthority> authorities = new ArrayList<>(convert);
        if(CollectionUtils.isNotEmpty(roles)){
            authorities.addAll(roles.stream().map(SimpleGrantedAuthority::new).toList());
        }
        return authorities;
    }



}
